package com.scs.application.modules.device.service.impl;

import cn.hutool.core.util.ObjectUtil;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.scs.application.core.exception.BusinessException;
import com.scs.application.core.flow.FlowContext;
import com.scs.application.core.service.BaseServiceImpl;
import com.scs.application.modules.device.entity.*;
import com.scs.application.modules.device.enums.DeviceBusMap;
import com.scs.application.modules.device.mapper.DevicePlanMapper;
import com.scs.application.modules.device.service.DevicePlanItemService;
import com.scs.application.modules.device.service.DevicePlanService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Lazy;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.io.Serializable;
import java.util.Collection;
import java.util.List;
import java.util.stream.Collectors;

/**
 *  设备计划 服务实现类
 */
@Service
public class DevicePlanServiceImpl extends BaseServiceImpl<DevicePlanMapper, DevicePlan> implements DevicePlanService {
    @Lazy
    @Autowired
    private DevicePlanItemService devicePlanItemService;

    @Override
    public boolean saveOrUpdate(DevicePlan entity) {
        if (entity.isNewRecord()) {
            entity.setBusKey(serialRuleAdapter.getSerialRuleService().generateCode(DeviceBusMap.getSerialKey(entity.getBusType())));
        }
        return super.saveOrUpdate(entity);
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public boolean removeCascadeByIds(Collection<? extends Serializable> idList) {
        List<String> childIdList = devicePlanItemService.list(Wrappers.<DevicePlanItem>query().in("plan_id", idList)).stream().map(DevicePlanItem::getId).collect(Collectors.toList());
        if (ObjectUtil.length(childIdList) > 0) {
            devicePlanItemService.removeCascadeByIds(childIdList);
        }

        return super.removeCascadeByIds(idList);
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public void afterHandleFlowChange(FlowContext flowContext, DevicePlan newEntity) {
        List<DevicePlanItem> childList = devicePlanItemService.list(Wrappers.<DevicePlanItem>query().eq("plan_id", newEntity.getId()));
        BusinessException.throwErrorIf(ObjectUtil.length(childList) == 0, "业务明细为空，无法审核通过");


        if (!flowContext.isEndNode()) {
            return;
        }
    }
}